define(['moment'], function (moment) {
    return ['$scope', '$rootScope', '$mdDialog', 'MMWService', '$filter', '$stateParams', 'config', '$document',
        function ($scope, $rootScope, $mdDialog, $MMWService, $filter, $stateParams, config, $document) {

            $scope.init = function(){
                $scope.tab_mode = 'L';
                $scope.LoadAccDetails = [];
                $scope.unLoadAccDetails = [];
                $scope.IsAutoUnload = 'N';
                $scope.loadAcc_barcode = '';
                $scope.unLoadAcc_barcode = '';
                $scope.mode = 'batch'; //single=單筆模式, batch=批次模式

                $scope.ProductList = []; // 产品编号列表
                if($stateParams.data.machine){
                    $scope.machine = $stateParams.data.machine;
                    if($stateParams.data.machine != ''){
                        $scope.mode = 'single';
                    }
                } else {
                    $scope.machine = {
                        machine_type: '',
                        machine_no: ''
                    }
                }
                // 20231116 modify by shiwl 0147604: 手机版上下模未上模清单显示错误
                machine_working_info_get($stateParams.data.machine_no, function(){
                    getAccessoryData();
                });

               
            };
          
            function machine_working_info_get(machine_no, feedback)  {
                var content = {
                    machine_no: machine_no,
                   // lot_no: $scope.lot_no,
                    data_type : '0001'
                };

                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_EQP.machine_working_info_get',
                    content : content,
                    success : function(data){
                       if(data.machine_production_info_detail.length>0 ){

                          data.machine_production_info_detail.forEach((item)=>{
                            if($scope.ProductList.indexOf(item.item_no)==-1){
                                $scope.ProductList.push(item.item_no);
                             }
                          });         
                       }
                        if(feedback)
                            feedback();
                    }
                });
            };
            $scope.back = function(){
                // 20200506 modify by Oliver for 回上一頁
                $rootScope.changeProgram('home', true);
            };

            // 設備
            $scope.input_machine_no = function(event){
                if(event.keyCode == 13){
                    input_machine_no_callback();
                } else {
                    $scope.machine.machine_no = $scope.machine.machine_no || '';
                }
            };

            // 設備 callback
            function input_machine_no_callback(){
                //檢查輸入的對不對
                pageNumberInfoGet($scope.machine.machine_no,function(itemList){
                    if(itemList && itemList.length > 0){
                        $scope.machine.machine_type = itemList[0].machine_type;
                        getAccessoryData(function(unLoadAccDetails, LoadAccDetails){
                            if(unLoadAccDetails.length !=0 || LoadAccDetails.length !=0){
                                getAccessoryData();
                            } else {
                                $scope.$root.showAlert($filter('translate')('common.msg.no_data'));
                            }
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('mobile10.msg.no_match_machine'));
                    }
                })

            }

            // 設備 info_get
            function pageNumberInfoGet(machine_no, callback){
                var query_condition_info = [];
                query_condition_info.push({column_name:'A.EquipmentNo', query_mode:'0', value:machine_no, merge_condition_model:'AND' });
                $MMWService.pageNumberInfoGet({
                    page_mode: 'rollback_work_set_info_get',
                    query_condition_info:query_condition_info
                }, function(itemList){
                    if(callback)
                        callback(itemList);
                });
            }

            $scope.loadMachineList = function () {
                $rootScope.showQueryList({
                    header : [
                        {label:$filter('translate')('common.queryList.machine_c'), code:'machine_no'},
                        {label:$filter('translate')('common.queryList.machine_n'), code:'machine_type'}
                    ],
                    query: function(conditions, feedback){
                        pageNumberInfoGet($scope.machine.machine_no, function(itemList){
                            feedback(itemList);
                        });
                    },
                    confirm : function(selectItem, dialog){
                        $scope.machine.machine_no = selectItem.machine_no;
                        $scope.machine.machine_type = selectItem.machine.machine_type;
                        dialog.hide();
                        input_machine_no_callback();
                    }
                });
            };

            // 模具編號
            $scope.input_mold_no = function(event){
                if(event.keyCode == 13){
                    var isMatch = false;
                    $scope.LoadAccDetails.forEach(function(item){
                        if(item.AccessoryNo == $scope.barcode_mold_no){
                            item.isSelect = true;
                            isMatch = true;
                        }else{
                            item.isSelect = false;
                        }
                    });
                    if(!isMatch){
                        $scope.unLoadAccDetails.forEach(function(item){
                            if(item.AccessoryNo == $scope.barcode_mold_no){
                                item.isSelect = true;
                                isMatch = true;
                            }else{
                                item.isSelect = false;
                            }
                        });
                        if(isMatch){
                            $scope.LoadAccToEquipment();
                        } else {
                            $rootScope.showToast($filter('translate')('mobile10.msg.no_match_accDetails'), 'error');
                        }
                    } else {
                        $scope.UnLoadAccFromEquipment();
                    }
                }
            }

            $scope.QRCodeScanner = function(target_id){
                $scope.$root.OpenScanner({
                    after : function(result){
                        if(target_id == 'input_machine'){
                            $scope.machine.machine_no = result.text;
                            input_machine_no_callback();
                        }else if(target_id == 'input_mold'){
                            $scope.barcode_mold_no = result.text;
                            $scope.input_mold_no();
                        }
                    },
                    exception: function(){
                        //目前裝置無法使用相機
                        $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                    },
                    orientation : 'portrait'
                });
            };

            // 是否自動下線
            $scope.clickIsAutoUnload = function(){
                if($scope.IsAutoUnload == 'Y'){
                    $scope.IsAutoUnload = 'N';
                } else {
                    $scope.IsAutoUnload = 'Y';
                }
            };

            $scope.getTabSize_load = function(){
                var Size = 0;
                if($scope.LoadAccDetails){
                    Size = $scope.LoadAccDetails.length
                }
                return Size;

            }
            $scope.getTabSize_unload = function(){
                var Size = 0;
                if($scope.unLoadAccDetails){
                    Size = $scope.unLoadAccDetails.length
                }
                return Size;
            };

            // 20220414 modify by Alan for#109789 : 修正取得模具資料時，未傳入設備編號，修正排版
            // 取得模具資料
            function getAccessoryData(callback){
                var unLoadAcc_content = {
                    EquipmentType: $scope.machine.machine_type,
                    EQUIPMENTNO: $scope.machine.machine_no,
                    ProductList: $scope.ProductList
                };
                var unLoadAccDetails = [];
                var LoadAccDetails = [];
                // 可用模具查詢 function
                LoadAppliedAccessory(unLoadAcc_content, function(data){
                    if(data[0].AccessoryNo !==null) {
                        unLoadAccDetails = data;
                    }
                    $scope.unLoadAccDetails = unLoadAccDetails;
                    var LoadAcc_content = {
                        EQUIPMENTTYPE: $scope.machine.machine_type,
                        EQUIPMENTNO : $scope.machine.machine_no
                    };

                    //已上機模具資訊查詢
                    LoadOnEquipmentAccessory(LoadAcc_content, function(data){
                        if(data[0].AccessoryNo !==null) {
                            LoadAccDetails = data;
                        }
                        $scope.LoadAccDetails = LoadAccDetails;
                        if(callback) {
                            callback(unLoadAccDetails,LoadAccDetails);
                        }
                    });
                });
            }

            //可用模具查詢
            function LoadAppliedAccessory(content, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_ACC.load_applied_acc_info_get',
                    content : content,
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            }

            //已上機模具資訊查詢
            function LoadOnEquipmentAccessory(content, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_ACC.load_on_machine_acc_info_get',
                    content : content,
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            }

            //模具上機作業
            function LoadAccToEquipment(content, callback){
                content.pTable = content.pTable;
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_ACC.load_applied_acc_to_machine_process',
                    content : content,
                    success : function(data){
                        if(callback)
                            callback(data);
                    }
                });
            }

            //模具下機作業
            function UnLoadAccFromEquipment(content, callback){
                content.pTable = content.pTable;
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_ACC.unload_acc_from_machine_process',
                    content : content,
                    success : function(data){
                        if(data.exec_result == 0){
                           $rootScope.showConfirm(data.message, function(dialog){
                                dialog.hide();
                                content.enforce = 1;
                                UnLoadAccFromEquipment(content, callback);
                           });
                        }else{
                            if(callback)
                                callback(data);
                        }
                    }
                });
            }

            //異常下機作業
            function funUnloadAccessory_Scrap(content, callback){
                $MMWService.sendToServer({
                    uri : 'ServicesSTD.Module_ACC.unload_scrap_acc_from_machine_process',
                    content : content,
                    success : function(data){
                        if(data.exec_result == 0){
                            $rootScope.showConfirm(data.message, function(dialog){
                                 dialog.hide();
                                 content.enforce = 1;
                                 funUnloadAccessory_Scrap(content, callback);
                            });
                         }else{
                            $rootScope.showToast($filter('translate')('common.msg.success'));
                            if(callback)
                                callback(data);
                         }
                    }
                });
            }

            // 異常下模開窗
            function openExceptionDialog(exception_acc_details, callback){
                var now_date = new Date();
                $mdDialog.dialog(
                    'module/moduleMobile/program/mobile10/mobile10.exception.html',
                    function (dialog) {
                        return {
                            next_date:now_date,
                            now_date:now_date,
                            exception_reason_display:'',
                            back:function(){
                                dialog.hide();
                            },
                            loadExceptoinReason:function(){
                                $MMWService.showQueryListPNIG({
                                    page_mode: 31,
                                    key:'page_no',
                                    header: [
                                        {label:$filter('translate')('mobile10.exception.acc_exption_reason_c'), code:'page_no'},
                                        {label:$filter('translate')('mobile10.exception.acc_exption_reason_n'), code:'page_name'}
                                    ],
                                    confirm : function(selectItem){
                                        dialog.exception_reason = selectItem.page_no;
                                        dialog.exception_reason_display = selectItem.page_no + ' / '+selectItem.page_name;
                                    }
                                });
                            },
                            confirm:function(){
                                if(dialog.exception_reason_display == ''){
                                    $rootScope.showAlert($filter('translate')('mobile10.msg.exception_reason_empty'));
                                } else {
                                    var content = {
                                        next_date:moment(dialog.next_date).format('YYYY-MM-DD'),
                                        reason_no:dialog.exception_reason,
                                        scrap_details:[]
                                    };
                                    exception_acc_details.forEach(function(detail){
                                        content.scrap_details.push({accessory_no:detail.AccessoryNo, machine_no: $scope.machine.machine_no});
                                    });
                                    funUnloadAccessory_Scrap(content, function(){
                                        dialog.hide();
                                        if(callback)
                                            callback();
                                    });
                                }
                            }
                        };
                    }
                );
            }

            // 下模
            $scope.UnLoadAccFromEquipment = function () {
                //檢核是否有勾選
                var machine = {
                    machine_type: $scope.machine.machine_type,
                    machine_no: $scope.machine.machine_no
                }
                var content = {
                    pTable:[]
                };

                $scope.LoadAccDetails.forEach(function(detail){
                    if(detail.isSelect){
                        content.pTable.push({
                            EQUIPMENTTYPE: machine.machine_type,
                            EQUIPMENTNO: machine.machine_no,
                            ACCESSORYTYPE: detail.AccessoryType,
                            ACCESSORYNO: detail.AccessoryNo,
                            ACCSerialNo:detail.ACCSerialNo,
                            USERNO: config.cache.account,
                            STARTTIME:moment(new Date()).format('YYYY-MM-DD'),
                            ACCESSORYVERSION: detail.AccessoryVersion
                        });
                    }
                });
                if(content.pTable.length != 0){
                    UnLoadAccFromEquipment(content, function(){
                        //重新取得畫面上的資料
                        getAccessoryData(function(unLoadAccDetails, LoadAccDetails){
                            LoadAccDetails_isSelectAll = false;
                            unLoadAccDetails_isSelectAll = false;
                            unLoadAccDetails = unLoadAccDetails;
                            LoadAccDetails = LoadAccDetails;
                            unLoadAcc_barcode = '';
                        });
                    });
                } else {
                    $rootScope.showAlert($filter('translate')('mobile10.msg.unLoadAccDetails_empty'));
                }
            };

            // 上膜
            $scope.LoadAccToEquipment = function () {//上架
                //檢核是否有勾選
                var machine = {
                    machine_type: $scope.machine.machine_type,
                    machine_no: $scope.machine.machine_no
                }
                var content = {
                    IsAutoUnload : $scope.IsAutoUnload,
                    pTable:[]
                };
                $scope.unLoadAccDetails.forEach(function(detail){
                    if(detail.isSelect){
                        content.pTable.push({
                            EQUIPMENTTYPE: machine.machine_type,
                            EQUIPMENTNO: machine.machine_no,
                            ACCESSORYTYPE:detail.AccessoryType,
                            ACCESSORYNO:detail.AccessoryNo,
                            ACCSerialNo:detail.ACCSerialNo,
                            USERNO:config.cache.account,
                            STARTTIME:moment(new Date()).format('YYYY-MM-DD'),
                            ACCESSORYVERSION: detail.AccessoryVersion
                        });
                    }
                });

                if(content.pTable.length != 0){
                    LoadAccToEquipment(content, function(){
                        //重新取得畫面上的資料
                        getAccessoryData(function(unLoadAccDetails, LoadAccDetails){
                            LoadAccDetails_isSelectAll = false;
                            unLoadAccDetails_isSelectAll = false;
                            unLoadAccDetails = unLoadAccDetails;
                            LoadAccDetails = LoadAccDetails;
                            loadAcc_barcode = '';
                        });
                    });
                } else {
                    $rootScope.showAlert($filter('translate')('mobile10.msg.LoadAccDetails_empty'));
                }
            };

            // 異常下模
            $scope.UnLoadAccException = function(){
                //20180904 add by Dustdusk for M#46551:增加異常下模功能
                //檢核是否有勾選
                var machine = {
                    machine_type: $scope.machine.machine_type,
                    machine_no: $scope.machine.machine_no
                }
                var exception_acc_details = [];
                $scope.LoadAccDetails.forEach(function(detail){
                    if(detail.isSelect){
                        exception_acc_details.push(detail);
                    }
                });

                if(exception_acc_details.length != 0){
                    openExceptionDialog(exception_acc_details, function(){
                        //重新取得畫面上的資料
                        getAccessoryData(function(unLoadAccDetails, LoadAccDetails){
                            LoadAccDetails_isSelectAll = false;
                            unLoadAccDetails_isSelectAll = false;
                            unLoadAccDetails = unLoadAccDetails;
                            LoadAccDetails = LoadAccDetails;
                        });
                    });
                } else {
                    $rootScope.showAlert($filter('translate')('mobile10.msg.ExceptionAccDetails_empty'));
                }
            };
        }
    ];
});
